// @ts-nocheck
import {
  LockOutlined,
  UserOutlined
} from '@ant-design/icons';
import {Alert, message} from 'antd';
import React, {useEffect, useState} from 'react';
import {ProFormText, LoginForm} from '@ant-design/pro-form';
import {useIntl, history, FormattedMessage, useModel} from 'umi';
import {login} from '@/services/ant-design-pro/api';
import title from '@/assets/title.png'
import bg from '@/assets/login.jpg'
import styles from './index.less';
import leftTop from '@/assets/1.png';
import {getPageImg} from "@/services/pageImg";

const LoginMessage: React.FC<{
  content: string;
}> = ({content}) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const {initialState, setInitialState} = useModel('@@initialState');

  const intl = useIntl();
  useEffect(() => {
    // @ts-ignore
    getPageImg().then((res) => {
      if (res.status === 200 && res.data.length !== 0) {
        sessionStorage.setItem('登录logo', res.data.filter((q: { [x: string]: string; }) => q['name_id'] == '1')[0]['img'])
        sessionStorage.setItem('左上方logo', res.data.filter((q: { [x: string]: string; }) => q['name_id'] == '2')[0]['img'])
        sessionStorage.setItem('左上方文字', res.data.filter((q: { [x: string]: string; }) => q['name_id'] == '3')[0]['text'])
      }
    })
  }, [])
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const msg = await login({...values, type});
      if (msg.status === 200) {
        sessionStorage.setItem('token', msg.token)
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        const {query} = history.location;
        const {redirect} = query as { redirect: string };
        history.push(redirect || '/welcome');
        return;
      }
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      message.error(defaultLoginFailureMessage);
    }
  };
  const {status, type: loginType} = userLoginState;
  return (
    <div className={styles.main}
         style={{background: '50%/cover url("https://zos.alipayobjects.com/rmsportal/gGlUMYGEIvjDOOw.jpg") no-repeat'}}>
      <div className={styles.container}>
        <LoginForm
          logo={<div
            style={{width: '80px', height: '80px', backgroundColor: 'white', borderRadius: '50%', overflow: 'hidden'}}>
            <img alt="logo" src={sessionStorage.getItem('登录logo') ? sessionStorage.getItem('登录logo') : title}
                 style={{padding: '5px'}}/>
          </div>}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          {status === 'error' && loginType === 'account' && (
            <LoginMessage
              content={intl.formatMessage({
                id: 'pages.login.accountLogin.errorMessage',
                defaultMessage: '账户或密码错误(admin/ant.design)',
              })}
            />
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon}/>,
                }}
                placeholder={'请输入用户名'}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入用户名!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon}/>,
                }}
                placeholder={'请输入密码'}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                ]}
              />
            </>
          )}
        </LoginForm>
      </div>
      <div className={styles.desc}>Copyright©2020-2025 版权所有 <br/>
        辽宁XXXXX有限公司<br/>
        经营许可证编号：XXXXXXXXXX
      </div>
    </div>
  );
};

export default Login;
